import importlib
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"


def autoBackend(backend_type, **kwargs):
    model_path = kwargs["model_path"]
    if not os.path.exists(model_path):
        raise FileNotFoundError(f"Model file '{model_path}' does not exist.")

    if backend_type == "pt":
        module_name = "geartrain.backends.pt_backend"
        class_name = "PT_Backend"
    elif backend_type == "ort":
        module_name = "geartrain.backends.ort_backend"
        class_name = "ORT_Backend"
    elif backend_type == "tf":
        module_name = "geartrain.backends.tf_backend"
        class_name = "TF_Backend"
    elif backend_type == "rknn":
        module_name = "geartrain.backends.rk_backend"
        class_name = "RKNN_Backend"
    elif backend_type == "x86rknn":
        module_name = "geartrain.backends.x86_rk_backend"
        class_name = "X86_RKNN_Backend"
    else:
        raise ValueError(f"Unsupported backend type: {backend_type}")

    # 动态导入模块
    module = importlib.import_module(module_name)

    # 获取类
    backend_class = getattr(module, class_name)

    # 实例化类
    backend_instance = backend_class(**kwargs)

    return backend_instance
